(function() {
	var _doc = document;
	function redirectMouseToTouch(type, originalEvent) {
		//stop propagation, and remove default behavior for everything but INPUT, TEXTAREA & SELECT fields		
		if (originalEvent.target.tagName.toUpperCase().indexOf("SELECT") == -1
				&& originalEvent.target.tagName.toUpperCase().indexOf(
						"TEXTAREA") == -1
				&& originalEvent.target.tagName.toUpperCase().indexOf("INPUT") == -1) //SELECT, TEXTAREA & INPUT
		{
			originalEvent.stopPropagation();
		}

		var touchevt = _doc.createEvent("Event");
		touchevt.initEvent(type, true, true);
		touchevt.touches = new Array();
		touchevt.touches[0] = new Object();
		touchevt.touches[0].pageX = originalEvent.pageX;
		touchevt.touches[0].pageY = originalEvent.pageY;
		touchevt.touches[0].target = originalEvent.target;
		touchevt.changedTouches = touchevt.touches; //for jqtouch
		touchevt.targetTouches = touchevt.touches; //for jqtouch
		touchevt.target = originalEvent.target;
		originalEvent.target.dispatchEvent(touchevt);
		return touchevt;
	}
	
	function emulateTouchEvents() {
		_doc.mouseMoving = false;
		_doc.addEventListener("mousedown", function(e) {
			try {
				this.mouseMoving = true;
				var touchevt = redirectMouseToTouch("touchstart", e);
				if (_doc.ontouchstart){
					_doc.ontouchstart(touchevt);
				}
				if (e.target.ontouchstart){
					e.target.ontouchstart(e);
				}

			} catch (e) {
			}
		});

		_doc.addEventListener("mouseup", function(e) {
			try {
				this.mouseMoving = false;
				var touchevt = redirectMouseToTouch("touchend", e);
				if (_doc.ontouchend){
					_doc.ontouchend(touchevt);
				}
				if (e.target.ontouchend){
					e.target.ontouchend(e);
				}
			} catch (e) {
			}
		});
		_doc.addEventListener("mousemove", function(e) {
			try {
				if (!this.mouseMoving){
					return;
				}
				var touchevt = redirectMouseToTouch("touchmove", e);
				if (_doc.ontouchmove)
					_doc.ontouchmove(touchevt);
				if (e.target.ontouchmove)
					e.target.ontouchmove(e);
			} catch (e) {
			}
		});
	}
	emulateTouchEvents();
	window.addEventListener("resize", function() {
		var touchevt = _doc.createEvent("Event");
		touchevt.initEvent("orientationchange", true, true);
		_doc.dispatchEvent(touchevt);
	}, false);
}());